//
//  CQStatuViewModel.swift
//  weibo
//
//  Created by chengqiang on 16/7/23.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit

class CQStatuViewModel: NSObject {
    //表示是否正在加载数据
    private var loadingStatus: Bool = false
    
   //单例
    static let sharedStatusViewModel:CQStatuViewModel = CQStatuViewModel()
    //获取用户界面信息
    func loadStatus(since_id:Int64,max_id:Int64, completion:(error: NSError?,statuModels: [CQstatus]?) -> Void) {
        
        if loadingStatus{
            let error = NSError(domain: "cn.itheima.network.loadstatus", code: -1, userInfo: ["errorDescription" : "有人正在加载微博数据,直接返回了"])
            completion(error: error,statuModels:nil)
            return
            
        }
        loadingStatus = true
        
        guard let access_token = CQUserViewModel.shareduserAccountViewModel.userAccount?.access_token else{
            print("access_token没有值")
            return
        }
        
        let urlstring = "2/statuses/home_timeline.json"
        var parameters:[String:AnyObject] = [
            "access_token":access_token,
            "count":5
        ]
        
        if since_id>0 {
            parameters["since_id"] = NSNumber(longLong:since_id)
            
        }else if max_id>0 {
            parameters["max_id"] = NSNumber(longLong:max_id-1)
        }
        //发送网络请求获取信息
        CQTool.sharedNetworking.GET(urlstring, parameters: parameters, progress: nil, success: { (_, responseObject)->
            Void in
            let responseDict = responseObject as?[String:AnyObject]
            
            
            let statusArray = responseDict?["statuses"] as?[[String:AnyObject]]
            
            var statuModels = [CQstatus]()
            
            for dict in statusArray!{
                let status = CQstatus(dict:dict)
                
                statuModels.append(status)
            }
            
            //回调获取到的信息
            completion(error: nil,statuModels: statuModels)
            
            self.loadingStatus = false
            
            }) { (_, error)-> Void in
                completion(error: error, statuModels: nil)
                self.loadingStatus = false
        }
        
    }
}
